import { Component, ChangeDetectorRef } from "@angular/core";
import {
  NavController,
  NavParams,
  ActionSheetController,
  AlertController,
  ToastController,
  LoadingController
} from "ionic-angular";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { appConfig } from "../../providers/config";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import { Storage } from "@ionic/storage";
import * as moment from "moment";
import { HttpService } from "../../providers/http.service";
import { HomePage } from "../home/home";
import { RescueDrillBean } from "./bean/RescueDrill";

@Component({
  selector: "page-rescus-drill",
  templateUrl: "rescue-drill.html"
})
export class RescuDrillPage {
  private images: any[] = [];
  private appConfig: any;
  private user: any;
  maintenancePartys: any = [];
  hm1: string;
  hm2: string;
  hm3: string;
  hm4: string;
  hm5: string;
  hm6: string;
  hm7: string;
  private time1 = new Date().getTime() + "1";
  private time2 = new Date().getTime() + "2";
  private time3 = new Date().getTime() + "3";
  rescueDrill: RescueDrillBean = new RescueDrillBean();
  canSubmit = false;
  showCheck: boolean = false;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private camera: Camera,
    private ActionSheet: ActionSheetController,
    private photoViewer: PhotoViewer,
    private transfer: FileTransfer,
    private file: File,
    private storage: Storage,
    private httpService: HttpService,
    private alert: AlertController,
    private toast: ToastController,
    private loadding: LoadingController,
    public cd: ChangeDetectorRef,
    private actionSheet: ActionSheetController,
  ) {
    this.appConfig = appConfig;
    //获取当前用户的信息
    this.rescueDrill.elevatorNum = this.navParams.get("elevatorNum");
    this.storage.get("user").then(data => {
      this.user = data;
      this.rescueDrill.drillPartyName = data.partyName;
      this.rescueDrill.drillRecordUserName = this.user.userName; //演练记录人姓名
    });

    this.storage.get("rescueDrill").then(data =>{
       //获取缓存数据
        if (data != null) {
          this.rescueDrill = data;
          this.hm1 = data.h1 +":" + data.m1 ;
          this.hm2 = data.h2 +":" + data.m2 ;
          this.hm3 = data.h3 +":" + data.m3 ;
          this.hm4 = data.h4 +":" + data.m4 ;
          this.hm5 = data.h5 +":" + data.m5 ;
          this.hm6 = data.h6 +":" + data.m6 ;
          this.hm7 = data.h7 +":" + data.m7 ;
        }
    });
  }

    ionViewWillLeave() {
        //数据缓存
        try {
            this.rescueDrill.h1 = this.hm1.split(":")[0];
            this.rescueDrill.m1 = this.hm1.split(":")[1];
            this.rescueDrill.h2 = this.hm2.split(":")[0];
            this.rescueDrill.m2 = this.hm2.split(":")[1];
            this.rescueDrill.h3 = this.hm3.split(":")[0];
            this.rescueDrill.m3 = this.hm3.split(":")[1];
            this.rescueDrill.h4 = this.hm4.split(":")[0];
            this.rescueDrill.m4 = this.hm4.split(":")[1];
            this.rescueDrill.h5 = this.hm5.split(":")[0];
            this.rescueDrill.m5 = this.hm5.split(":")[1];
            this.rescueDrill.h6 = this.hm6.split(":")[0];
            this.rescueDrill.m6 = this.hm6.split(":")[1];
            this.rescueDrill.h7 = this.hm7.split(":")[0];
            this.rescueDrill.m7 = this.hm7.split(":")[1];
        } catch (e) {
            console.log(e);
        }finally {
            this.storage.set("rescueDrill",this.rescueDrill);
        }

    }
  doCamera(i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(
          appConfig.IP_URL + appConfig.API.upload
        );
        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.images.push(aa["data"]);
              } else {
                this.images[i] = aa["data"];
              }
            }
          }
          this.cd.detectChanges();
        });
      },
      err => {
        // Handle error
      }
    );
  }

  onHold(param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.images.indexOf(param);
            this.doCamera(i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(url, null, { share: false });
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.images.indexOf(param);
            this.images.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  doConfirm() {
    if (!this.canSubmit) {
      const alertcc = this.alert.create({
        // title: '',
        subTitle: "维保单位不正确，请重新输入",
        buttons: ["确定"]
      });
      alertcc.present();
      return;
    }
    if (this.images.length <= 0) {
      this.alert
        .create({
          title: "错误",
          message: "请上传图片",
          buttons: ["确认"],
          enableBackdropDismiss: true
        })
        .present();
      return;
    }
    let load = this.loadding.create({
      spinner: appConfig.spinner,
      duration: appConfig.timeout
    });

    let data = moment(new Date()).format("YYYYMMDD");
    let image = this.images.join(",");
    try {
      this.rescueDrill.drillDate = data; //演练日期
      this.rescueDrill.drillPartyId = this.user.partyId; //演练单位id
      this.rescueDrill.drillPartyName = this.user.partyName; //演练单位名称
      this.rescueDrill.drillRecordUserId = this.user.id; //演练记录人id

      this.rescueDrill.picUrl = image; //演练照片

      this.rescueDrill.drillStdt = this.rescueDrill.drillStdt.split(":")[0];
      this.rescueDrill.drillEdt = this.rescueDrill.drillEdt.split(":")[0];
      this.rescueDrill.h1 = this.hm1.split(":")[0];
      this.rescueDrill.m1 = this.hm1.split(":")[1];
      this.rescueDrill.h2 = this.hm2.split(":")[0];
      this.rescueDrill.m2 = this.hm2.split(":")[1];
      this.rescueDrill.h3 = this.hm3.split(":")[0];
      this.rescueDrill.m3 = this.hm3.split(":")[1];
      this.rescueDrill.h4 = this.hm4.split(":")[0];
      this.rescueDrill.m4 = this.hm4.split(":")[1];
      this.rescueDrill.h5 = this.hm5.split(":")[0];
      this.rescueDrill.m5 = this.hm5.split(":")[1];
      this.rescueDrill.h6 = this.hm6.split(":")[0];
      this.rescueDrill.m6 = this.hm6.split(":")[1];
      this.rescueDrill.h7 = this.hm7.split(":")[0];
      this.rescueDrill.m7 = this.hm7.split(":")[1];
    } catch (error) {
      let tt = this.toast.create({
        message: "请填写完整信息！",
        duration: 2000,
        position: "top"
      });
      tt.present();
      return;
    }

      for (let i = 0; i <this.maintenancePartys.length ; i++) {
          if (this.maintenancePartys[i].partyName = this.rescueDrill.maintenancePartyName) {
              this.rescueDrill.maintenancePartyId = this.maintenancePartys[i].id;
          }
      }

    for (const key in this.rescueDrill) {
      if (this.rescueDrill.hasOwnProperty(key)) {
        const element = this.rescueDrill[key];
        if (!element) {
          let tt = this.toast.create({
            message: "请填写完整信息！",
            duration: 2000,
            position: "top"
          });
          tt.present();
          return;
        }
      }
    }
    load.present();
    this.httpService.rescueDrillAdd(this.rescueDrill).subscribe(
      data => {
        load.dismiss();
        if (data["status"] == 200) {
          let tt = this.toast.create({
            message: "提交成功",
            duration: 2000,
            position: "top"
          });
          tt.present().then(() => {
            this.navCtrl.setRoot(HomePage).then(()=>{
                this.storage.remove("rescueDrill");
              }
            );

          });
        } else {
          this.alert
            .create({
              title: "错误",
              message: data["message"],
              buttons: ["确认"],
              enableBackdropDismiss: true
            })
            .present();
        }
      },
      error => {
        load.dismiss();
      }
    );
  }

  getSafeImgUrl(param) {
    this.rescueDrill.safeUserSign = param.imageDate;
  }
  getMaint1ImgUrl(param) {
    this.rescueDrill.maintSing1 = param.imageDate;
  }
  getMaint2ImgUrl(param) {
    this.rescueDrill.maintSing2 = param.imageDate;
  }

  queryParty() {
      this.maintenancePartys = [];
      if (this.rescueDrill.maintenancePartyName) {
          let param = {partyName: this.rescueDrill.maintenancePartyName};
          this.httpService.queryPartyByNameLk(param).subscribe(data => {
              let temp = [];
              if (data.status == 200) {
                  temp = data.data;
                  if (temp != null) {
                      for (let i = 0; i < temp.length; i++) {
                          if (temp[i].partyType == "1") {
                              this.maintenancePartys.push(temp[i]);
                          }
                      }
                  }
                  this.showCheck = true;
                  this.canSubmit = true;
              } else {
                  this.maintenancePartys = [];
                  this.rescueDrill.maintenancePartyId = "0";
                  this.canSubmit = true;
              }
          });
      }
    }

  //
    presentActionSheet(i) {
        let buttonList: any = [];
        buttonList.push({
            text: "拍照",
            role: "拍照",
            handler: () => {
                let options: CameraOptions = {
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
                        options.fileKey = "file";
                        options.fileName = "test.jpg";
                        options.mimeType = "image/jpeg";
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul["response"]);
                            if (aa["status"] == 200) {
                                if (aa["data"].length > 0) {
                                    if (i == "c") {
                                        this.images.push(aa["data"]);
                                    } else {
                                        this.images[i] = aa["data"];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });
        buttonList.push({
            text: "从相册选择照片",
            role: "从相册选择照片",
            handler: () => {
                let options: CameraOptions = {
                    sourceType: 0,
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
                        options.fileKey = "file";
                        options.fileName = "test.jpg";
                        options.mimeType = "image/jpeg";
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul["response"]);
                            if (aa["status"] == 200) {
                                if (aa["data"].length > 0) {
                                    if (i == "c") {
                                        this.images.push(aa["data"]);
                                    } else {
                                        this.images[i] = aa["data"];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });

        buttonList.push({
            text: "取消",
            role: "取消",
            handler: () => { }
        });

        let actionSheet = this.actionSheet.create({ buttons: buttonList });
        actionSheet.present();
    }
}
